<template>
  <div class="bandWidth">
    <div class="view">
      <div class="usertop flexc">
        <span class="flex title" v-if="!status">{{ $t('tronExchange.FreezeUnfreeze') }} {{ $t('tronExchange.bandwidth') }}</span>
        <span class="flex title" v-else>{{ $t('tronExchange.FreezeUnfreeze') }} {{ $t('tronExchange.energy') }}</span>
      </div>
      <div class="ram">
        <div class="zjType flexb">
          <div class="tab" v-for="(item, index) in activeList"
          :key="index"
          :class="{'active': activeIndex === item.id}"
          @click="handleActiveMenu(item.id)">
            {{item.label}}
          </div>
        </div>
        <!-- 冻结 -->
        <div class="pd8px" v-if="!activeIndex">
          <!-- 接收地址 -->
          <div class="term flexb">
            <div class="termWord">{{ $t('exchange.receivingAddress1') }}</div>
            <div class="cycle">
              <el-input v-model.trim="accountName"
              clearable
              :placeholder="$t('tronExchange.doNotFillIn')"></el-input>
            </div>
          </div>
          <!-- 冻结数量 -->
          <div class="term term1 flexb">
            <div class="termWord">{{ $t('tronExchange.frozenQuantity') }}</div>
            <div class="cycle">
              <el-input
              type="number"
              v-model="frozenNumber">
                <span slot="suffix">TRX</span>
              </el-input>
            </div>
          </div>
          <!-- 余额 -->
          <div class="right reduceBalance" v-if="scatter.identity">
            {{$t('myWallet.balance')}}：{{balance}} TRX
          </div>
          <el-button class="qrbtn"
            @click="handleFrozenSubmit"
            v-loading="loading">
            {{$t('public.sure')}}
          </el-button>
          <div class="wordTip">
            *{{ $t('tronExchange.frozenTip') }}
          </div>
        </div>
        <!-- 解冻 -->
        <div class="pd8px thaw" v-loading="laodingForUnlock" v-else>
          <div class="unlockedTit center">{{$t('newpos.toBeUnlocked')}}</div>
          <div class="unlockedNum center">{{back.frozenBalance}} TRX</div>
          <div class='unlockedTime flexb' v-if="back.expireTime && back.frozenBalance">
            <span>{{ $t('tronExchange.frozenTime') }}</span>
            <span>{{back.expireTime}}</span>
          </div>
          <el-button
            class="thawBtn"
            @click="handleUnfreezeBalance"
            type="primary"
            v-loading="loading"
            :disabled="!back.frozenBalance || !isOverTeday">
            {{$t('public.sure')}}
          </el-button>
          <div class="thawTip" v-if="back.fromAther"> {{back.fromAther}}TRX{{ $t('tronExchange.freezingByOther') }}</div>
          <div class="forOthers flexb" v-if="back.toAther">
            <span>{{ $t('tronExchange.freezeForOthers') }}{{back.toAther}} TRX</span>
            <span class="colorThis" style="cursor: pointer;" @click="leaseListVisible = true;">{{ $t('tronExchange.frozen') }}</span>
          </div>
        </div>
      </div>
    </div>
    <!-- 租借列表/带宽、能量 -->
    <el-dialog
      :visible.sync="leaseListVisible"
      width="650px"
      append-to-body
      center
      :close-on-click-modal="false">
      <lease-list
      :back="back"
      :status="status"
      :leaseListVisible="leaseListVisible"
      @listenLeaseList="handleLeaseList"/>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment';
import { EosModel } from '@/utils/eos';
import LeaseList from '@/views/myWallet/tronResource/LeaseList'; // 租借列表

export default {
  name: 'bandWidth', // 能量/带宽
  data() {
    return {
      laodingForUnlock: false,
      loading: false,
      balance: 0,
      isOverTeday: 0,
      activeIndex: 0, // 0冻结 1解冻
      scatter: {
        identity: null,
      },
      activeList: [
        {
          id: 0,
          label: this.$t('tronExchange.frozened')
        },
        {
          id: 1,
          label: this.$t('tronExchange.frozen')
        }
      ],
      frozenNumber: 0, // 冻结数量
      accountName: '', // 接收地址
      leaseListVisible: false, // 租借列表
      back: {},
    }
  },
  components: {
    LeaseList
  },
  props: {
    status: Number, // 0带宽 1能量
    bandWidthVisible: Boolean
  },
  watch: {
    '$store.state.app.scatter.identity': {
      handler: function listen() {
        this.scatter = this.$store.state.app.scatter;
        this.accountName = this.scatter.identity.accounts[0].name;
      },
      deep: true,
    },
    bandWidthVisible: function change(val) {
      if (val) {
        this.handleMounted()
      }
    },
    '$store.state.app.language': function change() {
      this.activeList = [
        {
          id: 0,
          label: this.$t('tronExchange.frozened')
        },
        {
          id: 1,
          label: this.$t('tronExchange.frozen')
        }
      ]
    }
  },
  computed: {},
  created() {},
  mounted() {
    this.handleMounted();
  },
  beforeDestroy() {},
  methods: {
    // 切换
    handleActiveMenu(val) {
      this.activeIndex = val;
      if (val === 1) {
        this.handleGetFreeznList();
      }
    },
    // 冻结操作
    handleFrozenSubmit() {
      const params = {
        amount: Number(this.frozenNumber),
        resource: this.status,
        address: this.accountName,
      }
      if (params.amount < 1) {
        this.$message.error(this.$t('tronExchange.freezeLeast'));
        return;
      }
      this.loading = true;
      EosModel.freezeBalance(params, (res) => {
        this.loading = false;
        if (res && res.result) {
          this.$message.success(`${this.$t('newpos.successfulOperation')}，${this.$t('public.fewMins')}`);
          setTimeout(() => {
            this.handleGetBalance();
          }, 3500)
          return;
        }
        this.$message.error(res);
      });
    },
    // 解冻操作
    handleUnfreezeBalance() {
      const params = {
        resource: this.status,
        address: null,
      }
      this.laodingForUnlock = true;
      EosModel.unfreezeBalance(params, (res) => {
        if (res && res.result) {
          this.$message.success(`${this.$t('newpos.successfulOperation')}，${this.$t('public.fewMins')}`);
          this.laodingForUnlock = true;
          // 再次获取数据
          setTimeout(() => {
            this.handleGetFreeznList();
            this.handleGetBalance();
          }, 3500)
          return;
        }
        this.laodingForUnlock = false;
        this.$message.error(res);
      })
    },
    async handleGetBalance() {
      const res = await EosModel.getTronBalance('', 'trx');
      this.balance = res.trx;
    },
    // 列表回调
    handleLeaseList(val) {
      this.leaseListVisible = false;
      if (val === 'close') return;
      this.laodingForUnlock = true;
      // 再次获取数据
      setTimeout(() => {
        this.handleGetFreeznList();
        this.handleGetBalance();
      }, 3500)
    },

    // 获取冻结列表
    handleGetFreeznList() {
      this.laodingForUnlock = true;
      this.back.frozenBalance = null;
      this.back.expireTime = null;
      this.back.toAther = null; // 自己给别人的冻结
      this.back.fromAther = null; // 来自别人的冻结
      EosModel.freeznList((res) => {
        // 0带宽 1能量
        if (this.status === 0) {
          this.back.frozenBalance = res.meToMeBandwidth.frozen_balance; // 带宽待解锁额度
          const time = this.handleTimeFormat(res.meToMeBandwidth.expire_time);
          this.back.expireTime = time; // 待解锁时间
          this.isOverTeday = res.meToMeEnergy.expire_time - (new Date().getTime()) < 0;
          this.back.toAther = Number(res.allBandwidthToOther);
          this.back.fromAther = Number(res.allBandwidthFromOther);
          this.back.list = res.meToAther.filter(v => v.type === 'bandwidth');
        }
        if (this.status === 1) {
          this.back.frozenBalance = res.meToMeEnergy.frozen_balance; // 能量待解锁额度
          const time = this.handleTimeFormat(res.meToMeEnergy.expire_time);
          this.back.expireTime = time; // 待解锁时间
          this.isOverTeday = res.meToMeEnergy.expire_time - (new Date().getTime()) < 0;
          this.back.toAther = Number(res.allEnergyToOther);
          this.back.fromAther = Number(res.allEnergyForOther);
          this.back.list = res.meToAther.filter(v => v.type === 'energy');
        }
        this.$forceUpdate();
        this.laodingForUnlock = false;
        // console.log(this.back);
      });
    },
    handleMounted() {
      this.laodingForUnlock = false;
      this.loading = false;
      this.activeIndex = 0; // 0冻结 1解冻
      this.scatter = this.$store.state.app.scatter;
      this.accountName = this.scatter.identity.accounts[0].name;
      this.handleGetBalance();
    },
    handleTimeFormat(value) {
      // const zone = moment().zone() / 60; // 时区
      // .add(0 - zone, 'hours')
      return moment(value).format('YYYY/MM/DD HH:mm:ss');
    },
  },
}
</script>
<style lang="scss" scoped>
@import '@/views/myWallet/user.scss';
@import '@/assets/css/variables.scss';
@import '@/views/myWallet/eosResource/resource.scss';

.mcbtn, .mrbtn {
  height: 40px;
  font-size: 14px;
}

.mrbtn {
  width: 100%;
  color: #fff;
  background-color: $-btn-green;
  border-color: $-btn-green;
  -webkit-box-shadow: -1px 0 0 0 $-btn-green;
  box-shadow: -1px 0 0 0 $-btn-green;
}
.mcbtn {
  width: 100%;
  color: #fff;
  background-color: $-btn-red;
  border-color: $-btn-red;
  -webkit-box-shadow: -1px 0 0 0 $-btn-red;
  box-shadow: -1px 0 0 0 $-btn-red;
}

.qrbtn {
  width: 100%;
  color: #fff;
  background-color: $-btn-blue;
  border-color: $-btn-blue;
  -webkit-box-shadow: -1px 0 0 0 $-btn-blue;
  box-shadow: -1px 0 0 0 $-btn-blue;
}

.zjType {
  // padding: 0 10px;
  .tab {
    position: relative;
    display: inline-block;
    width: 47%;
    padding: 10px 0;
    border-radius: 3px;
    color: #333;
    border: 1px solid #e4e7ed;
    text-align: center;
    cursor: pointer;
  }

  .tab:first-child {
    margin-right: 15px;
  }

  .active {
    color: $-btn-blue;
    border-color: $-btn-blue;
  }
}

.view{
  box-shadow: none;
  .usertop {
    font-size: 18px;
    padding-top: 0;
    text-align: center;

    &::before {
      display: none;
    }

    .title {
      font-size: 16px;
    }
  }
  .ram {
    padding: 20px 40px 20px 40px;
  }

  .tip2 {
    padding-left: 75px;
  }

  /deep/ .el-button {
    padding: 12px 20px;
  }

  .term {
    margin-top: 10px;

    &.term1 {
      margin: 10px 0 10px 0;
    }

    .termWord {
      flex: 1;
    }

    .cycle {
      flex: 4;
      width: 235px;
      min-width: 235px;
      position: relative;

      /deep/ .el-input-number {
        width: 100%;
      }
      /deep/ .el-input__suffix {
        line-height: 40px;
      }
    }
  }

  .reduceBalance {
    margin-bottom: 30px;
  }

  .wordTip {
    color: #999;
    margin-top: 20px;
  }

  .thaw {
    .unlockedTit {
      margin: 20px 0 10px 0;
    }

    .unlockedNum {
      font-size: 18px;
      margin-bottom: 10px;
    }

    .unlockedTime {
      background-color: rgba(246, 218, 177, 0.34);
      color: #FF9800;
      padding: 5px 15px;
      margin-bottom: 10px;
    }

    .thawBtn {
      width: 100%;
      margin-bottom: 5px;
    }

    .thawTip {
      color: #FF9800;
      margin-bottom: 10px;
    }
  }
}
.theme-1B1D27{
  .zjType {
    .tab {
      color: rgba(255, 255, 255, 0.5);
      border-color: RGBA(197, 206, 228, 0.3);
    }
    .tab.active {
      color: $-btn-blue;
      border-color: $-btn-blue;
    }
  }
  .mask {
    background: #152247 !important;
  }
}
</style>

